<!-- @format -->

<template>
  <view class="red-flower">
    <wd-navbar fixed placeholder safeAreaInsetTop>
      <template #left>
        <view class="nav-left">
          <the-capsule></the-capsule>
          <!-- 用户列表 -->
          <the-users
            :users="users"
            :current-user="currentUser"
            :addEnabled="addUserEnabled"
            @change="toSwitchUser"
            @add="onAddUser"
          ></the-users>
        </view>
      </template>
    </wd-navbar>

    <!-- 统计面板 -->
    <view class="stats-panel">
      <view class="stat-item">
        <text class="stat-value">{{ available }}</text>
        <text class="stat-label">朵可用</text>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <the-icon-btn
          title="兑换"
          @click="showUseDialog"
          bgColor="green"
          icon="gift"
        />

        <the-icon-btn
          bgColor="white"
          color="#222"
          :border="false"
          :paddingOuter="false"
          size="50rpx"
          @click="showLogDialog"
          icon="error-circle"
        />
      </view>
    </view>

    <view class="calendar-container">
      <wd-calendar-view
        ref="calendarRef"
        v-model="selectedDate"
        :max-date="maxDate"
        :formatter="formatter"
        :panel-height="160"
      >
      </wd-calendar-view>
    </view>

    <view class="record-x">
      <!-- 消息说明 -->
      <!-- 已有记录 -->
      <view class="record-append-x">
        <view class="label-x">
          <view class="label-title">备注：</view>
          <input class="label-input" type="text" v-model="markText" />
        </view>
        <view class="record-opes">
          <wd-rate
            v-model="rate"
            size="60rpx"
            icon="chrome"
            active-icon="chrome-filled"
            active-color="red"
          ></wd-rate>

          <the-icon-btn
            bgColor="green"
            icon="edit"
            @click="onRecord"
            title="奖励"
          >
          </the-icon-btn>
        </view>
      </view>
      <!-- 已有记录 -->
      <view v-show="currentSelectItem" class="record-list-x">
        <view class="record-title">已有记录：</view>
        <view
          v-for="item in currentSelectItemRecord"
          :key="item.date"
          class="record-list-item"
        >
          <text>事件：{{ item.mark }}</text>

          <wd-rate
            :modelValue="item.amount"
            size="40rpx"
            icon="chrome"
            active-icon="chrome-filled"
            active-color="red"
          ></wd-rate>
        </view>
      </view>
    </view>

    <!-- 使用弹窗 -->
    <wd-popup v-model="showUse" position="top">
      <view class="dialog-container">
        <view class="label-title">兑换数：</view>

        <wd-input-number
          v-model="useAmount"
          :min="0"
          :max="available"
          :step="2"
          input-width="200rpx"
        />

        <view class="label-x">
          <view class="label-title">备注：</view>
          <input class="label-input" type="text" v-model="markText" />
        </view>

        <the-icon-btn
          title="确认"
          icon="check-bold"
          bgColor="red"
          @click="onUse"
        ></the-icon-btn>
      </view>
    </wd-popup>

    <!-- 日志弹窗 -->
    <wd-popup v-model="showLog" position="bottom">
      <view class="dialog-title">兑换记录</view>
      <scroll-view class="log-list" scroll-y>
        <view v-if="!useLogs.length" class="tip-empty">-- 暂无记录 --</view>
        <view
          v-else
          v-for="(log, index) in useLogs"
          :key="index"
          class="log-item"
        >
          <view class="log-item-info">
            <view>{{ log.mark }} </view>
            <view style="color: red">
              {{ log.amount }}
              <the-icon icon="chrome"></the-icon>
            </view>
          </view>
          <view class="log-date">{{ log.date }}</view>
        </view>
      </scroll-view>
    </wd-popup>

    <wd-toast></wd-toast>
  </view>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useToast } from 'wot-design-uni'
import { useRedFlower } from '../../composables/useRedFlower'
import { getDateYMD, preventRepeatedClick } from '../../utils/commonUtils'

const toast = useToast()

const showUse = ref(false)
const showLog = ref(false)

const calendarRef = ref(null)

const userSwitching = ref(false)

const rate = ref(0)
const useAmount = ref(0)
const markText = ref('')

const today = Date.now()
const selectedDate = ref(today)
const maxDate = ref(today)

const {
  users,
  currentUser,
  content,
  useContent,
  useLogs,
  queryData,
  updateAmount,
  updateUse,
  addUser,
  changeUser,
  switchUser,
} = useRedFlower()

const formatter = (day) => {
  const key = getDateYMD(day.date)
  if (content.value[key]) {
    day.bottomInfo = content.value[key].total
  }
  return day
}

const addUserEnabled = computed(() => {
  return users.value.length < 3
})

const available = computed(() => {
  // 正在切换用户时，为0
  if (userSwitching.value) return 0

  let result = 0
  if (content.value) {
    result = Object.values(content.value).reduce((total, cur) => {
      if (cur?.total) {
        return total + cur.total
      }
    }, 0)
  }
  if (useContent.value) {
    // 减去兑换的数量
    const usedCount = Object.values(useContent.value).reduce((total, cur) => {
      if (cur?.total) {
        return total + cur.total
      }
      return total
    }, 0)
    result = result - usedCount
  }
  return result
})

const currentSelectItem = computed(() => {
  const key = getDateYMD(selectedDate.value)
  return content.value[key] || 0
})

const currentSelectItemRecord = computed(() => {
  return currentSelectItem.value?.list || []
})

watch(content, () => {
  refreshCalendar()
})

watch(currentSelectItem, () => {
  if (currentSelectItemRecord.value.length > 0) {
    markText.value = currentSelectItemRecord.value[0].mark
  }
})

const initData = async () => {
  await queryData()
  toSwitchUser(users.value[0])
}

// 初始化加载本地数据
onMounted(() => {
  // 获取数据
  initData()
  // 滚动到当前日期
  calendarRef.value?.scrollIntoView()
})

const toSwitchUser = async (user) => {
  if (!user) return
  if (userSwitching.value) return
  showUse.value = false

  userSwitching.value = true
  await switchUser(user)
  userSwitching.value = false
}

const showUseDialog = () => {
  if (available.value < 1) {
    toast.show('没有可用的小红花')
    return
  }
  markText.value = ''
  showUse.value = true
}

const showLogDialog = () => {
  showLog.value = true
}

const onAddUser = preventRepeatedClick(async (params) => {
  const { isAdd = false, userName = '', callback } = params || {}

  if (!userName) {
    toast.show('请输入名称')
    return
  }

  if (isAdd) {
    const data = await addUser(userName)
    toast.show('添加成功')

    callback && callback(false)

    await switchUser(data)
  } else {
    // 编辑
    await changeUser({ ...currentUser.value, name: userName })
    toast.show('操作成功')

    callback && callback(false)
  }
})

const onRecord = preventRepeatedClick(async () => {
  // 保存当前日期选择的小红花数量
  // 数量
  const amount = rate.value
  if (!amount) {
    toast.show('请选择小红花数量')
    return
  }
  const date = getDateYMD(selectedDate.value)
  const history = content.value[date]
  const item = { amount, date: Date.now(), mark: markText.value || '奖励' }
  let data
  if (history) {
    history.total += amount
    history.list.push(item)
    data = history
  } else {
    data = { total: amount, list: [item] }
  }

  await updateAmount({
    [date]: data,
  })

  toast.show('操作成功')
})

// 兑换小红花
const onUse = preventRepeatedClick(async () => {
  const amount = useAmount.value

  if (!amount) {
    toast.show('请输入兑换数量')
    return
  }

  const date = getDateYMD(selectedDate.value)
  const history = useContent.value[date]
  const logs = { amount, date: Date.now(), mark: markText.value }
  let data
  if (history) {
    history.total += amount
    history.list.unshift(logs)
    data = history
  } else {
    data = { total: amount, list: [logs] }
  }
  await updateUse({
    [date]: data,
  })
  toast.show('操作成功')

  setTimeout(() => {
    markText.value = ''
    showUse.value = false
  }, 100)
})

let change = 1
const refreshCalendar = () => {
  maxDate.value = today + change
  change = change * -1
}
</script>

<style scoped lang="scss">
.mb-10 {
  margin-bottom: 20rpx;
}

.nav-left {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.calendar-day {
  position: relative;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stats-panel {
  position: relative;
  margin: 40rpx;
  padding: 40rpx 20rpx;
  background: linear-gradient(135deg, #fff5f5, #fff);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(229, 77, 66, 0.1);
  display: flex;
  /* justify-content: space-around; */
  align-items: flex-end;
  gap: 40rpx;
}

.user-setting {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
}

.stat-item {
  padding: 20rpx 40rpx;
  min-width: 200rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stat-value {
  font-size: 56rpx;
  color: green;
  font-weight: 800;
  position: relative;
  margin-bottom: 16rpx;
}

.stat-label {
  margin: 0 8rpx;
  font-size: 24rpx;
  color: #666;
}

.stat-item.small {
  box-shadow: none;
  background-color: transparent;
}
.stat-item.small .stat-value {
  font-size: 40rpx;
  color: #333;
}

.action-buttons {
  // margin: 40rpx;

  display: flex;
  align-items: center;

  gap: 20rpx;
}

.action-buttons .wd-button {
  flex: 1;
  border-radius: 12rpx;
  padding: 24rpx 0;
  font-size: 28rpx;
}

.calendar-container {
  padding-bottom: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.record-x {
  // background-color: #f8f8f8;
  border-radius: 8rpx;
  margin: 20rpx;
  padding: 20rpx;
}
.record-append-x {
  padding-bottom: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}
.record-opes {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40rpx;
}

.record-list-x {
  margin-top: 30rpx;
}

.record-title {
  text-align: center;

  color: #666;
  font-size: 28rpx;
}

.record-list-item {
  margin: 20rpx 0;
  display: flex;
  justify-content: space-between;
  font-size: 28rpx;
}

/* 修改记录和使用弹窗容器 */
.dialog-container {
  padding: 40rpx;
  padding-top: 280rpx;
  // padding-bottom: calc(40rpx + env(safe-area-inset-bottom)); /* 新增安全底部 */
  border-radius: 32rpx 32rpx 0 0;
}

.label-x {
  margin: 8rpx 0;
}

.label-title {
  font-size: 24rpx;
  color: #222;
  margin: 8rpx 0;
}

.label-input {
  border: 1px solid #ddd;
  padding: 8rpx;
}

:deep(.wd-month__day-bottom:not(:empty)) {
  text-align: center;
  color: green;
  font-weight: bold;
  font-size: 28rpx;
  bottom: 4rpx;
  &::before {
    content: '+';
  }
}

:deep(.wd-month__day.is-selected .wd-month__day-container) {
  .wd-month__day-bottom:not(:empty) {
    color: white;
  }
}

/* 调整日志弹窗高度 */
.log-list {
  min-height: calc(60vh - env(safe-area-inset-bottom));
  width: 100%;
  padding: 20rpx 40rpx;
  box-sizing: border-box;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); /* 安全底部 */
}

.tip-empty {
  font-size: 24rpx;
  color: #333;
  text-align: center;
  margin: 80rpx 0;
}

.log-item {
  margin-bottom: 20rpx;
  padding-top: 4rpx;
}

.log-item-info {
  display: flex;
  justify-content: space-between;
}

.dialog-title {
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
  padding: 20rpx 0;
}
.log-date {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #666;
}
</style>
